DEFINING AND CALLING FUNCTIONS
In Python, functions are blocks of reusable code that perform a specific task. They help in breaking down the code into smaller, more manageable pieces and promote code reusability. To define and call functions in Python, follow these steps:
1. Defining a Function: You define a function using the def
keyword followed by the function name, a pair of parentheses ()
, and a colon :
. The function body is indented under the def
statement.
def greet():
print("Hello, World!")
In the example above, we define a function named greet()
that prints "Hello, World!" when called.
2. Calling a Function: To call a function, you simply write the function name followed by parentheses ()
.
greet() # Output: Hello, World!
When you call the function greet()
, it executes the code inside the function body and prints "Hello, World!".
3. Functions with Parameters: You can define functions that accept parameters to perform actions based on the provided values.
def greet_person(name):
print(f"Hello, {name}!")
greet_person("Alice") # Output: Hello, Alice!
greet_person("Bob") # Output: Hello, Bob!
In this example, we define a function named greet_person()
that takes a name
parameter and prints a personalized greeting.
4. Functions with Return Values: Functions can also return values using the return
statement. The function will execute the code and provide a result back to the caller.
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result) # Output: 8
The function add_numbers()
takes two parameters a
and b
and returns their sum.
5. Default Parameters: You can set default values for function parameters. If the caller does not provide a value, the default value will be used.
def multiply(a, b=2):
return a * b
print(multiply(5)) # Output: 10 (2 is used as the default value for b)
print(multiply(5, 3)) # Output: 15 (3 is provided as the value for b)
In the example above, multiply()
has a default value of 2 for the b
parameter.
6. Function Documentation (Docstrings): You can add documentation to your functions using docstrings. Docstrings are triple-quoted strings placed immediately after the function definition.
def my_function(parameter):
"""
This is a docstring that explains what the function does.
"""
# Function code here
Now you know how to define and call functions in Python. Functions are an essential aspect of programming, enabling you to write modular and reusable code for various tasks.